<template>
  <div class="admin-container">
    <!-- 页面标题与操作区 -->
    <div class="page-header">
      <h2>管理员-访客管理</h2>
      <div class="operation-btns"></div>
    </div>

    <!-- 搜索区 -->
    <div class="search-bar">
      <input
        type="text"
        v-model="searchPhone"
        placeholder="输入手机号搜索"
        class="search-input"
      />
      <button class="btn primary" @click="fetchGuestList">搜索</button>
      <button class="btn default" @click="resetSearch">重置</button>
    </div>

    <!-- 访客列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>用户名</th>
            <th>手机号</th>
            <th>邮箱</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="guest in guestList" :key="guest.userId">
            <td>{{ guest.account }}</td>
            <td>{{ guest.phone }}</td>
            <td>{{ guest.email || "-" }}</td>
            <td>
              <span
                class="status-tag"
                :class="guest.status === '0' ? 'banned' : 'active'"
              >
                {{ guest.status === "0" ? "封禁" : "正常" }}
              </span>
            </td>
            <td class="operation-col">
              <button
                class="btn text"
                :class="guest.status === '0' ? 'success' : 'danger'"
                @click="handleStatusChange(guest)"
              >
                {{ guest.status === "0" ? "解封" : "封禁" }}
              </button>
            </td>
          </tr>
          <tr v-if="guestList.length === 0">
            <td colspan="5" class="empty-state">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <span class="total">共 {{ total }} 条记录</span>
      <button
        class="btn default"
        @click="changePage(pageNum - 1)"
        :disabled="pageNum <= 1"
      >
        上一页
      </button>
      <span class="page-info">第 {{ pageNum }} / {{ totalPages }} 页</span>
      <button
        class="btn default"
        @click="changePage(pageNum + 1)"
        :disabled="pageNum >= totalPages"
      >
        下一页
      </button>
    </div>

    <!-- 提示消息 -->
    <div class="toast" v-if="toastMessage">{{ toastMessage }}</div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import { inMemoryStorage } from "/src/router/index.js";
import { useRouter } from "vue-router";

const router = useRouter();

// axios 基础配置
axios.defaults.baseURL = "http://localhost:8080";
axios.defaults.withCredentials = true;
axios.defaults.headers.common["Accept"] = "application/json";
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";

// 请求拦截器：附带 token
axios.interceptors.request.use(
  (config) => {
    const token = inMemoryStorage.token || "";
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    } else if (!config.url.includes("/login")) {
      router.replace("/");
      showToast("请先登录");
      return Promise.reject(new Error("未登录"));
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器：统一处理错误
axios.interceptors.response.use(
  (response) => {
    if (typeof response.data === "string") {
      showToast(response.data);
    }
    return response;
  },
  (error) => {
    if (error.response) {
      const status = error.response.status;
      const message = error.response.data || "操作失败";
      showToast(`[${status}] ${message}`);
      if (status === 401) {
        inMemoryStorage.token = null;
        router.replace("/");
        showToast("登录已失效，请重新登录");
      }
    } else if (error.request) {
      showToast("无法连接服务器，请检查后端是否启动");
    } else {
      showToast("请求异常：" + error.message);
    }
    return Promise.reject(error);
  }
);

// 分页相关
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const totalPages = computed(() => Math.ceil(total.value / pageSize.value) || 1);

// 数据与搜索
const guestList = ref([]);
const allGuests = ref([]);
const searchPhone = ref("");

// 提示消息
const toastMessage = ref("");

// 获取访客列表
const fetchGuestList = async () => {
  try {
    const response = await axios.post(
      "/user/admin/guestSelect",
      {},
      { params: { pageNum: pageNum.value } }
    );

    if (response.data.message === "查询成功") {
      allGuests.value = response.data.list || [];
      total.value = response.data.total || 0;
      pageSize.value = response.data.pageSize || 10;
      filterGuestsByPhone();
    } else {
      showToast("获取数据失败：" + (response.data.message || "未知错误"));
    }
  } catch (error) {
    console.error("获取访客列表失败:", error);
    showToast("网络错误或权限不足");
  }
};

// 搜索过滤
const filterGuestsByPhone = () => {
  const phoneStr = searchPhone.value.trim();
  if (!phoneStr) {
    guestList.value = [...allGuests.value];
  } else {
    guestList.value = allGuests.value.filter(
      (guest) => guest.phone === phoneStr
    );
  }
};

// 搜索
const resetSearch = () => {
  searchPhone.value = "";
  pageNum.value = 1;
  fetchGuestList();
};

// 切换分页
const changePage = (num) => {
  if (num >= 1 && num <= totalPages.value) {
    pageNum.value = num;
    fetchGuestList();
  }
};

// 显示提示
const showToast = (msg) => {
  toastMessage.value = msg;
  setTimeout(() => (toastMessage.value = ""), 3000);
};

// 封禁 / 解封操作
const handleStatusChange = async (guest) => {
  const isBanned = guest.status === "0";
  const actionText = isBanned ? "解封" : "封禁";
  const apiUrl = isBanned ? "/user/admin/statusUnban" : "/user/admin/statusBan";

  if (!confirm(`确定要${actionText}该访客吗？`)) return;

  try {
    await axios.post(apiUrl, {}, { params: { phone: guest.phone } });
    showToast(`${actionText}成功`);
    fetchGuestList();
  } catch (error) {
    console.error(`${actionText}失败：`, error);
    showToast(`${actionText}失败，请重试`);
  }
};

// 页面初始化
onMounted(() => {
  fetchGuestList();
});
</script>
<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-btns {
  display: flex;
  gap: 10px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 0 0 300px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #eee;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f9f9f9;
  font-weight: 600;
}

.select-col {
  width: 50px;
}

.operation-col {
  display: flex;
  gap: 10px;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 封禁状态（红色背景+文字） */
.status-tag.banned {
  background-color: #fde2e2;
  color: #f5222d;
}

/* 正常状态（绿色背景+文字） */
.status-tag.active {
  background-color: #e1f3d8;
  color: #52c41a;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  justify-content: flex-end;
}

.total {
  color: #666;
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 6px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 20px;
}

.modal-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin: 0;
}

.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  z-index: 1001;
  animation: fadein 0.3s, fadeout 0.3s 2.7s;
}

/* 按钮样式 */
.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn.primary {
  background-color: #409eff;
  color: white;
}

.btn.primary:hover:not(:disabled) {
  background-color: #66b1ff;
}

.btn.danger {
  background-color: #f5222d;
  color: white;
}

.btn.danger:hover:not(:disabled) {
  background-color: #ff4d4f;
}

.btn.warning {
  background-color: #faad14;
  color: white;
}

.btn.warning:hover:not(:disabled) {
  background-color: #ffc53d;
}

.btn.default {
  background-color: #f5f5f5;
  color: #333;
}

.btn.default:hover:not(:disabled) {
  background-color: #e8e8e8;
}

.btn.text {
  background: none;
  color: #666;
  padding: 4px 8px;
}

.btn.text:hover {
  color: #409eff;
}

.btn.text.primary {
  color: #409eff;
}

.btn.text.danger {
  color: #f5222d;
}

.btn.text.success {
  color: #52c41a;
}

/* 动画效果 */
@keyframes fadein {
  from {
    top: 0;
    opacity: 0;
  }
  to {
    top: 20px;
    opacity: 1;
  }
}

@keyframes fadeout {
  from {
    top: 20px;
    opacity: 1;
  }
  to {
    top: 0;
    opacity: 0;
  }
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .admin-container {
    padding: 10px;
  }

  .search-input {
    flex: 1;
  }

  .operation-col {
    flex-direction: column;
    gap: 5px;
  }

  .modal {
    width: 90%;
  }
}
</style>
